<template>
  <el-autocomplete v-model="dataForm[tempAttrName]"
                   value-key="name"
                   autoComplete="on"
                   :placeholder="placeholder"
                   :select-when-unmatched="true"
                   :fetch-suggestions="querySearch"
                   :clearable="true"
                   @input="autocompleteInputHandler"
                   @select="setAutocompleteValue"
  ></el-autocomplete>
</template>

<script>
import basicMixins from './basicMixins'
import {mRequest} from '@/utils/request'

export default {
  name: 'autocomplete',
  props: {
    querySearchApiName: {
      type: String,
      required: true
    }
  },
  mixins: [basicMixins],
  data() {
    return {
      searchArray: [],
      tempAttrName: `autocompleteLabel-${this.attrName}`
    }
  },
  methods: {
    querySearch(queryString, cb) {
      cb(queryString ? this.filterSearch(queryString) : this.searchArray)
    },
    filterSearch(searchStr, equals = false) {
      const searchFunc = equals ? this.R.equals : this.R.includes

      return this.R.filter((item) => searchFunc(searchStr.toLowerCase(), item['name'].toLowerCase()), this.searchArray)
    },
    autocompleteInputHandler(value) {
      this.forceUpdate()

      if (this.R.equals(value, '')) {
        // eslint-disable-next-line no-undefined
        this.dataForm[this.attrName] = undefined
      }
    },
    setAutocompleteValue(value) {
      this.dataForm[this.attrName] = this.R.prop('id', value)
    }
  },
  mounted() {
    mRequest(this.querySearchApiName, {}, ({data}) => {
      this.searchArray = data['list']
    })
  }
}
</script>

<style scoped>

</style>
